#include "databasemanager.h"
#include <QDir>
#include <QStandardPaths>

DatabaseManager::DatabaseManager(QObject *parent)
    : QObject(parent)
    , m_isConnected(false)
{
    // 初始化数据库连接
    connectDatabase();
}

DatabaseManager::~DatabaseManager()
{
    closeDatabase();
}

bool DatabaseManager::connectDatabase()
{
    // 设置数据库类型为SQLite
    m_database = QSqlDatabase::addDatabase("QSQLITE");
    
    // 设置数据库文件路径
    QString dbPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir().mkpath(dbPath);
    m_database.setDatabaseName(dbPath + "/login_system.db");
    
    // 尝试连接数据库
    if (!m_database.open()) {
        qDebug() << "数据库连接失败:" << m_database.lastError().text();
        return false;
    }
    
    m_isConnected = true;
    qDebug() << "数据库连接成功";
    
    // 初始化数据库表
    return initializeDatabase();
}

void DatabaseManager::closeDatabase()
{
    if (m_database.isOpen()) {
        m_database.close();
        m_isConnected = false;
        qDebug() << "数据库连接已关闭";
    }
}

bool DatabaseManager::isConnected() const
{
    return m_isConnected;
}

bool DatabaseManager::initializeDatabase()
{
    // 创建用户表
    if (!createUserTable()) {
        return false;
    }
    
    // 插入默认管理员账户
    insertDefaultAdmin();
    
    return true;
}

bool DatabaseManager::createUserTable()
{
    QSqlQuery query;
    QString createTableSQL = 
        "CREATE TABLE IF NOT EXISTS users ("
        "id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "username TEXT UNIQUE NOT NULL,"
        "password TEXT NOT NULL,"
        "register_time DATETIME DEFAULT CURRENT_TIMESTAMP"
        ")";
    
    if (!query.exec(createTableSQL)) {
        qDebug() << "创建用户表失败:" << query.lastError().text();
        return false;
    }
    
    qDebug() << "用户表创建成功";
    return true;
}

bool DatabaseManager::insertDefaultAdmin()
{
    // 检查是否已存在管理员账户
    if (isUsernameExists("admin")) {
        return true;
    }
    
    // 创建默认管理员账户
    User adminUser(1, "admin", "admin123", QDateTime::currentDateTime());
    return addUser(adminUser);
}

bool DatabaseManager::addUser(const User &user)
{
    QSqlQuery query;
    query.prepare("INSERT INTO users (username, password, register_time) VALUES (?, ?, ?)");
    query.addBindValue(user.getUsername());
    query.addBindValue(user.getPassword());
    query.addBindValue(user.getRegisterTime().toString("yyyy-MM-dd hh:mm:ss"));
    
    if (!query.exec()) {
        qDebug() << "添加用户失败:" << query.lastError().text();
        return false;
    }
    
    qDebug() << "用户添加成功:" << user.getUsername();
    return true;
}

bool DatabaseManager::removeUser(int userId)
{
    QSqlQuery query;
    query.prepare("DELETE FROM users WHERE id = ?");
    query.addBindValue(userId);
    
    if (!query.exec()) {
        qDebug() << "删除用户失败:" << query.lastError().text();
        return false;
    }
    
    return query.numRowsAffected() > 0;
}

bool DatabaseManager::updateUser(const User &user)
{
    QSqlQuery query;
    query.prepare("UPDATE users SET username = ?, password = ? WHERE id = ?");
    query.addBindValue(user.getUsername());
    query.addBindValue(user.getPassword());
    query.addBindValue(user.getId());
    
    if (!query.exec()) {
        qDebug() << "更新用户失败:" << query.lastError().text();
        return false;
    }
    
    return query.numRowsAffected() > 0;
}

User DatabaseManager::findUserByUsername(const QString &username)
{
    QSqlQuery query;
    query.prepare("SELECT id, username, password, register_time FROM users WHERE username = ?");
    query.addBindValue(username);
    
    if (query.exec() && query.next()) {
        User user;
        user.setId(query.value(0).toInt());
        user.setUsername(query.value(1).toString());
        // 从数据库读取的是已加密的哈希，避免二次加密
        user.setHashedPassword(query.value(2).toString());
        user.setRegisterTime(QDateTime::fromString(query.value(3).toString(), "yyyy-MM-dd hh:mm:ss"));
        return user;
    }
    
    return User(); // 返回空用户对象
}

User DatabaseManager::findUserById(int userId)
{
    QSqlQuery query;
    query.prepare("SELECT id, username, password, register_time FROM users WHERE id = ?");
    query.addBindValue(userId);
    
    if (query.exec() && query.next()) {
        User user;
        user.setId(query.value(0).toInt());
        user.setUsername(query.value(1).toString());
        // 从数据库读取的是已加密的哈希，避免二次加密
        user.setHashedPassword(query.value(2).toString());
        user.setRegisterTime(QDateTime::fromString(query.value(3).toString(), "yyyy-MM-dd hh:mm:ss"));
        return user;
    }
    
    return User(); // 返回空用户对象
}

QList<User> DatabaseManager::getAllUsers()
{
    QList<User> users;
    QSqlQuery query("SELECT id, username, password, register_time FROM users ORDER BY id");
    
    while (query.next()) {
        User user;
        user.setId(query.value(0).toInt());
        user.setUsername(query.value(1).toString());
        // 从数据库读取的是已加密的哈希，避免二次加密
        user.setHashedPassword(query.value(2).toString());
        user.setRegisterTime(QDateTime::fromString(query.value(3).toString(), "yyyy-MM-dd hh:mm:ss"));
        users.append(user);
    }
    
    return users;
}

bool DatabaseManager::isUsernameExists(const QString &username)
{
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM users WHERE username = ?");
    query.addBindValue(username);
    
    if (query.exec() && query.next()) {
        return query.value(0).toInt() > 0;
    }
    
    return false;
}
